package com.shierke.Ume.ui.activity.me

import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.app.TakePhotoImpl
import com.jph.takephoto.compress.CompressConfig
import com.jph.takephoto.model.CropOptions
import com.jph.takephoto.model.InvokeParam
import com.jph.takephoto.model.TContextWrap
import com.jph.takephoto.model.TResult
import com.jph.takephoto.permission.InvokeListener
import com.jph.takephoto.permission.PermissionManager
import com.jph.takephoto.permission.TakePhotoInvocationHandler
import com.shierke.Ume.R
import com.shierke.Ume.base.BaseActivity
import com.shierke.Ume.ui.adapter.me.SettingPhotoAdapter
import com.shierke.Ume.ui.view.SpaceItemDecoration
import com.shierke.Ume.util.startActivity
import kotlinx.android.synthetic.main.activity_my_profile.*
import java.io.File
import com.blankj.utilcode.util.FragmentUtils.setBackgroundColor
import androidx.recyclerview.widget.RecyclerView
import android.content.Context.VIBRATOR_SERVICE
import android.graphics.Color
import androidx.core.content.ContextCompat.getSystemService
import android.os.Vibrator
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.core.app.ComponentActivity.ExtraData
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.util.Log
import android.view.View
import android.widget.AdapterView
import com.shierke.Ume.util.click
import java.util.*


/**
 * Create by Ybx
 * on 2020-10-20
 * Desribe:
 */
class MyProfileActivity : BaseActivity(), TakePhoto.TakeResultListener, InvokeListener {


    override fun takeSuccess(result: TResult?) {

        val compressPath = result!!.image.compressPath
        settingPhotoAdapter.getPhotoList().add(compressPath)
        settingPhotoAdapter.notifyDataSetChanged()
    }

    override fun takeCancel() {
    }

    override fun takeFail(result: TResult?, msg: String?) {

    }

    override fun invoke(invokeParam: InvokeParam?): PermissionManager.TPermissionType {
        val type =
            PermissionManager.checkPermission(TContextWrap.of(this), invokeParam!!.getMethod())
        if (PermissionManager.TPermissionType.WAIT == type) {
            this.invokeParam = invokeParam
        }
        return type
    }


    fun getTakePhoto(): TakePhoto {
        if (takePhoto == null) {
            takePhoto = TakePhotoInvocationHandler.of(this).bind(
                TakePhotoImpl(
                    this,
                    this
                )
            ) as TakePhoto
        }
        //设置压缩规则，最大500kb
        takePhoto!!.onEnableCompress(CompressConfig.Builder().setMaxSize(100 * 1024).create(), true)
        return takePhoto!!

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        getTakePhoto().onActivityResult(requestCode, resultCode, data)

    }


    override fun onSaveInstanceState(outState: Bundle) {
        getTakePhoto().onSaveInstanceState(outState)
        super.onSaveInstanceState(outState)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val type =
            PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this)

    }

    private var takePhoto: TakePhoto? = null
    private var invokeParam: InvokeParam? = null

    companion object {

        fun startActivity(context: Context) {
            context.startActivity<MyProfileActivity>()

        }
    }


    private lateinit var settingPhotoAdapter: SettingPhotoAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_profile)
        setActivityTitleText(getString(R.string.my_setting_profile))



        settingPhotoAdapter = SettingPhotoAdapter({
            val file = File(externalCacheDir, System.currentTimeMillis().toString() + ".png")
            val uri = Uri.fromFile(file)
            val size = Math.min(
                resources.displayMetrics.widthPixels,
                resources.displayMetrics.heightPixels
            )
            val cropOptions =
                CropOptions.Builder().setOutputX(size).setOutputX(size).setWithOwnCrop(true)
                    .create()
            getTakePhoto().onPickFromGalleryWithCrop(uri, cropOptions)
        }, {
            helper.startDrag(it)
        })


        photoList.layoutManager = GridLayoutManager(this, 3)

        val decoration = SpaceItemDecoration(15)
        photoList.addItemDecoration(decoration)
        photoList.adapter = settingPhotoAdapter
        helper.attachToRecyclerView(photoList)




        signature.click { SettingSignActivity.startActivity(this) }

        setName.click { SettinggNameActivity.startActivity(this) }

        setLable.click { SettingTagActivity.startActivity(this) }

    }


    var helper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ): Int {
            var dragFrlg = 0
            if (recyclerView.layoutManager is GridLayoutManager) {
                dragFrlg =
                    ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
            } else if (recyclerView.layoutManager is LinearLayoutManager) {
                dragFrlg = ItemTouchHelper.UP or ItemTouchHelper.DOWN
            }
            return ItemTouchHelper.Callback.makeMovementFlags(dragFrlg, 0)
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            //滑动事件  下面注释的代码，滑动后数据和条目错乱，被舍弃
            //            Collections.swap(datas,viewHolder.getAdapterPosition(),target.getAdapterPosition());
            //            ap.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());


            //得到当拖拽的viewHolder的Position
            val fromPosition = viewHolder.adapterPosition
            //拿到当前拖拽到的item的viewHolder
            val toPosition = target.adapterPosition


            if (settingPhotoAdapter.getPhotoList().size > toPosition) {
                if (fromPosition < toPosition) {
                    for (i in fromPosition until toPosition) {
                        Collections.swap(settingPhotoAdapter.getPhotoList(), i, i + 1)
                    }
                } else {
                    for (i in fromPosition downTo toPosition + 1) {
                        Collections.swap(settingPhotoAdapter.getPhotoList(), i, i - 1)
                    }
                }
                settingPhotoAdapter.notifyItemMoved(fromPosition, toPosition)
                return true
            }

            return false

        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            //侧滑删除可以使用；
        }

        override fun isLongPressDragEnabled(): Boolean {
            return false
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         * @param viewHolder
         * @param actionState
         */
        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
//            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
//                viewHolder!!.itemView.setBackgroundColor(Color.RED)
//                //获取系统震动服务//震动70毫秒
//                val vib = getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
//                vib.vibrate(70.0)
//            }
            super.onSelectedChanged(viewHolder, actionState)
        }


        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
            super.clearView(recyclerView, viewHolder)
            viewHolder.itemView.setBackgroundColor(0)
            settingPhotoAdapter.notifyDataSetChanged()  //完成拖动后刷新适配器，这样拖动后删除就不会错乱
        }
    })

}